<script setup lang="ts">
import { FwbButton } from 'flowbite-vue';

const props = defineProps<{
    page: number,
    pageCount: number,
    loading?: boolean,
}>();

const emits = defineEmits<{
    (e: 'change', value: number): void,
    (e: 'prev'): void,
    (e: 'next'): void,
}>();

const page = ref(props.page);

const onSubmit = () => {
    let result = page.value;
    // standardize page number
    if (isNaN(result) || !Number.isInteger(result)) result = props.page;
    else if (result < 1) result = 1;
    else if (result > props.pageCount) result = props.pageCount;
    // emits
    page.value = result;
    emits('change', result);
};

watch(() => props.page, value => {
    page.value = value
});
</script>

<template>
    <footer class="w-full h-8 flex gap-3 justify-center items-center">
        <fwb-button gradient="cyan-blue" outline @click="$emit('prev')" :disabled="page === 1">
            <svg class="icon shrink-0" :style="{ margin: '-6px', width: '1.5rem', height: '1.5rem' }"
                aria-hidden="true">
                <use xlink:href="#icon-arrow-left-element" />
            </svg>
        </fwb-button>
        <input v-model.number="page" :disabled="loading === true" @blur="onSubmit" @keydown.enter="onSubmit"
            class="w-8 h-8 border-2 border-blue-500 rounded-md text-center text-blue-500 outline-offset-2 focus:outline-theme" />
        <fwb-button gradient="cyan-blue" outline @click="$emit('next')" :disabled="page === pageCount">
            <svg class="icon shrink-0" :style="{ margin: '-6px', width: '1.5rem', height: '1.5rem' }"
                aria-hidden="true">
                <use xlink:href="#icon-arrow-right-element" />
            </svg>
        </fwb-button>
    </footer>
</template>